/* eslint-disable jsdoc/check-param-names */
/* eslint-disable jsdoc/require-param */
/* eslint-disable jsdoc/require-returns */
// import { defineDirective } from "@/shared/define.js";
import { defineDirectiveLink } from "@/shared/tools.mjs";

export const playDraggableDirective = defineDirectiveLink(
  /**
   * @param {ng.IDocumentService} $document
   */
  ($document) => (scope, element, attrs, ctrl) => {
    let startX = 0;
    let startY = 0;
    let x = 0;
    let y = 0;
    // 帮HTML擦屁股
    element.css({
      position: "relative",
      border: "1px solid red",
      backgroundColor: "lightgrey",
      cursor: "pointer",
      display: "block",
      width: "max-content",
    });
    // if (!["relative",'absolute'].includes(element.css('position')) ){
    //   console.error('should set position to relative or absolute')
    //   return
    // }
    element.on("mousedown", (event) => {
      // Prevent default dragging of selected content
      event.preventDefault();
      startX = event.screenX - x;
      startY = event.screenY - y;
      $document.on("mousemove", mousemove);
      $document.on("mouseup", mouseup);
    });
    /**
     * @returns {void}
     */
    function mouseup() {
      $document.off("mousemove", mousemove);
      $document.off("mouseup", mouseup);
    }

    /**
     * @param {JQuery.Event & { screenX: number; screenY: number}} event
     */
    function mousemove(event) {
      y = event.screenY - startY;
      x = event.screenX - startX;
      /**
       * @type {{top?: string; left?: string;}}
       */
      const newPos = {};
      if (x > 0 && x < 800 - 20) {
        newPos.left = `${x}px`;
      }
      if (y > 0 && y < 600 - 20) {
        newPos.top = `${y}px`;
      }

      console.log(newPos);
      element.css(newPos);
    }
  },
  ["$document"],
);
